package com.dangdi.show.controller;

import com.aliyuncs.exceptions.ClientException;
import com.dangdi.show.enity.OrderInfo;
import com.dangdi.show.enity.PaymentConst;
import com.dangdi.show.service.ManagerService;
import com.dangdi.show.service.WechatUserService;
import com.dangdi.show.util.*;
import com.gexin.fastjson.JSONArray;
import com.gexin.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Max;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("wechat")
public class WechatController {
    @Autowired
    WechatUserService userService;
    @Autowired
    ManagerService managerService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //测试
    @RequestMapping("test")
    public String test() {
        logger.info("test方法进行测试");
        return "ok";
    }

    //添加地址
    @RequestMapping("addAddress")
    public Map<String, Object> addAddress(HttpServletRequest request, String address_tel, String yanzhengma, String address_name, String address_sheng, String address_shi, String address_qu, String address) {
        Map<String, Object> map = new HashMap<String, Object>();
        String openid = request.getSession().getAttribute("openid").toString();
        if (!request.getSession().getAttribute("phoneCode").equals(yanzhengma)) {
            map.put("statusCode", -1);
            map.put("msg", "验证码错误");
            return map;
        }
        if (!request.getSession().getAttribute("phoneCodePhone").equals(address_tel)) {
            map.put("statusCode", -1);
            map.put("msg", "请用收到验证码的手机号注册");
            return map;
        }
        userService.AddWecharUserAddress(address_name, address_tel, address_sheng, address_shi, address_qu, address, openid);
        map.put("statusCode", 0);
        map.put("msg", "添加成功");
        return map;
    }

    //修改地址
    @RequestMapping("updateAddress")
    public Map<String, Object> updateAddress(HttpServletRequest request, String address_tel, String address_name, String address_sheng, String address_shi, String address_qu, String address, int address_id) {
        Map<String, Object> map = new HashMap<String, Object>();
        int row = userService.updateAddress(address_name, address_tel, address_sheng, address_shi, address_qu, address, address_id);
        if (row > 0) {
            map.put("statusCode", 0);
            map.put("msg", "修改成功");
            return map;
        } else {
            map.put("statusCode", -1);
            map.put("msg", "修改失败");
        }
        return map;
    }

    @RequestMapping("getAddressList")
    public List<Map<String, Object>> getAddressList(HttpServletRequest request) {
        String openid = request.getSession().getAttribute("openid").toString();
        List<Map<String, Object>> addresList = userService.getAddressListByOpenId(openid);
        for (int i = 0; i < addresList.size(); i++) {
            addresList.get(i).put("user_tel", addresList.get(i).get("user_tel").toString().substring(0, 3) + "****" + addresList.get(i).get("user_tel").toString().substring(6, 10));
        }
        return addresList;
    }

    @RequestMapping("getAddressByAddressId")
    public Map<String, Object> getAddressByAddressId(int address_id) {
        Map<String, Object> addresList = userService.getAddressByAddressId(address_id);
        addresList.put("user_tel2", addresList.get("user_tel").toString().substring(0, 3) + "****" + addresList.get("user_tel").toString().substring(6, 10));
        return addresList;
    }

    @RequestMapping("del_address")
    public Map<String, Object> del_address(int address_id) {
        int row = userService.del_address(address_id);
        Map<String, Object> map = new HashMap<String, Object>();
        if (row > 0) {
            map.put("statusCode", 0);
            map.put("msg", "删除成功");
        } else {
            map.put("statusCode", -1);
            map.put("msg", "删除失败");
        }
        return map;
    }

    @RequestMapping("getProvinceList")
    public Map<String, Object> getProvinceList(int page, int limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> m = new HashMap<String, Object>();
        m.put("province_name", "请选择");
        m.put("city_name", "请选择");
        m.put("area_name", "请选择");
        List<Map<String, Object>> ls = managerService.getProvinceList((page - 1) * limit, limit);
        List<Map<String, Object>> ls2 = managerService.getCityList((page - 1) * limit, limit);
        List<Map<String, Object>> ls3 = managerService.getAreaList((page - 1) * limit, limit);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", 999999);
        ls.add(m);
        ls2.add(m);
        ls3.add(m);
        Collections.reverse(ls);
        Collections.reverse(ls2);
        Collections.reverse(ls3);
        map.put("data", ls);
        map.put("data2", ls2);
        map.put("data3", ls3);
        return map;
    }

    @RequestMapping("filterChengshi")
    public Map<String, Object> filterChengshi(HttpServletRequest request, int title, int page, int limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", 99999);
        if (title == 0) {
            map.put("data", managerService.getCityList((page - 1) * limit, limit));
            return map;
        }
        Map<String, Object> m = new HashMap<String, Object>();
        m.put("province_name", "请选择");
        m.put("city_name", "请选择");
        List<Map<String, Object>> ls = managerService.filterChengshi(title, (page - 1) * limit, limit);
        ls.add(m);
        Collections.reverse(ls);
        map.put("data", ls);
        return map;
    }

    @RequestMapping("xiadan")
    public Map<String, Object> xiadan(HttpServletRequest request, String code, int price, String date, String time, int address_id, String feeScale) throws Exception {
        JSONArray feeScale_id_list = JSONArray.parseArray(feeScale);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> mp = new HashMap<String, Object>();
        Date d = new Date();
        WechatApiUtil wechatApiUtil = new WechatApiUtil();
        String openID = WechatApiUtil.getOpenId(code);
        OrderInfo order = new OrderInfo();
        order.setAppid(PaymentConst.APP_ID);
        order.setMch_id("1518556491");
        order.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
        order.setBody("show");
        order.setOut_trade_no(sf.format(d) + address_id);
        order.setTotal_fee(price * 100 + "");
        order.setSpbill_create_ip(PaymentConst.HOST_IP);
        order.setNotify_url(PaymentConst.NOTIFY_URL);
        order.setTrade_type(PaymentConst.TRADE_TYPE);
//        order.setSign_type(PaymentConst.SIGN_TYPE);
        order.setOpenid(openID);
        order.setAttach("show");
        logger.info("即将签名");
        String sign = Signature.getSign(order);
        logger.info("签名=" + sign);
        order.setSign(sign);
        String xmData = Xml_MapUtils.mapToXml(MapObjUtil.object2SortMap(order));
//        System.out.println(xmData);
        HttpResponse response = HttpClientUtil.sendXMLDataByPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xmData);
//        System.out.println("------下单返回--------");
        HttpEntity entity = response.getEntity();
        String return_str = EntityUtils.toString(entity, "UTF-8");
        Map<String, Object> rt_map = Xml_MapUtils.xmlToMap(return_str);
//        System.out.println(rt_map);
//        System.out.println("------我是底线--------");
        if (!rt_map.get("return_code").equals("SUCCESS")) {
            map.put("code", -1);
            map.put("msg", rt_map.get("return_msg").toString());
            map.put("return_code", rt_map.get("return_code").toString());
            return map;
        }
        mp = userService.xiadan(price + "", order.getOpenid(), address_id, sf2.parse(date + " " + time), order.getOut_trade_no(), feeScale_id_list);
        int row = (int) mp.get("code");
        map.put("msg", mp.get("msg"));
        map.put("order_id", mp.get("order_id"));
        if (row != 1) {
            map.put("code", row);
            map.put("return_code_msg", rt_map.get("return_msg").toString());
            map.put("return_code", rt_map.get("return_code").toString());
            return map;
        }
//        System.out.println("到了这儿说明可以支付了");
        long Ltime = System.currentTimeMillis() / 1000;
        String timeStamp = String.valueOf(Ltime);
        Map<String, Object> twoSignInfo = new HashMap<String, Object>();
        twoSignInfo.put("appId", PaymentConst.APP_ID);
        twoSignInfo.put("timeStamp", timeStamp);
        twoSignInfo.put("nonceStr", RandomStringGenerator.getRandomStringByLength(32));
        twoSignInfo.put("package", "prepay_id=" + rt_map.get("prepay_id"));
        twoSignInfo.put("signType", "MD5");
        String twoSign = Signature.getSign(twoSignInfo);
        twoSignInfo.put("order_number", (sf.format(d) + address_id));
        twoSignInfo.put("paySign", twoSign);
        map.put("twoSign", twoSignInfo);
        map.put("code", 0);
        map.put("msg", rt_map.get("return_msg").toString());
        map.put("return_code", rt_map.get("return_code").toString());
        return map;
    }

    @RequestMapping("getOderList")
    public Map<String, Object> getOderList(HttpServletRequest request, int page, String code) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "获取成功！");
        List<Map<String, Object>> orderList = userService.getOrderList(WechatApiUtil.getOpenId(code), (page - 1) * 10);
        if (orderList.size() == 0) {
            map.put("code", -1);
            map.put("msg", "未查到订单信息");
            return map;
        }
        map.put("data", orderList);
        map.put("code", 0);
        System.out.println(map);
        return map;
    }


    @RequestMapping("getOrderInfo")
    public Map<String, Object> getOderInfo(HttpServletRequest request, int order_id) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "获取成功！");
        List<Map<String, Object>> orderInfo = userService.getOrderInfo(order_id);
        if (orderInfo == null) {
            map.put("code", -1);
            map.put("msg", "未查到订单信息");
            return map;
        }
        map.put("data", orderInfo);
        map.put("actorList", userService.getActorListByorder_id(order_id));
        map.put("code", 0);
        return map;
    }

    @RequestMapping("getPublishList")
    public Map<String, Object> getPublishList() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "获取成功");
        map.put("publishList", managerService.getPublishList(0, 99999));
        return map;
    }

    @RequestMapping("getFeeScaleListBypublish_id")
    public Map<String, Object> getFeeScaleListBypublish_id(int publish_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "获取成功");
        map.put("feeScaleList", managerService.getFeeScaleByPd_id(publish_id, 0, 99999));
        return map;
    }

    @RequestMapping("pay")
    public Map<String, Object> pay(String order_number) throws ClientException, InterruptedException {
        Map<String, Object> map = new HashMap<String, Object>();

        int row = userService.pay(order_number);
        if (row != 1) {
            map.put("code", -1);
            map.put("msg", "订单状态未改");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "支付成功");
        return map;
    }

    @RequestMapping("deleteOrder")
    public Map<String, Object> deleteOrder(int order_id) {
        Map<String, Object> map = new HashMap<>();
        int row = userService.deleteOrder(order_id);
        if (row != 1) {
            map.put("code", -1);
            map.put("msg", "删除失败");
        }
        map.put("code", 0);
        map.put("msg", "删除成功");
        return map;
    }

    @RequestMapping("getRefondTime")
    public Map<String, Object> getRefondTime(String order_number) {

        Map<String, Object> map = new HashMap<>();
        map.put("data", userService.getRefondTime(order_number));
        map.put("code", 0);
        map.put("msg", "获取成功");
        return map;
    }

    @RequestMapping("tuikuan")
    public Map<String, Object> tuikuan(String order_number, String total_fee, String refund_fee, int address_id) throws Exception {
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        SortedMap<String, Object> order = new TreeMap<String, Object>();
        order.put("appid", PaymentConst.APP_ID);
        order.put("mch_id", "1518556491");
        order.put("nonce_str", RandomStringGenerator.getRandomStringByLength(32));
        order.put("out_trade_no", order_number);
        order.put("out_refund_no", "TK" + order_number);
        order.put("total_fee", total_fee);
        order.put("refund_fee", refund_fee);
        order.put("transaction_id", "");
        String sign = Signature.getSign(order);
        order.put("sign", sign);
        String xmData = Xml_MapUtils.mapToXml(order);
        System.out.println(xmData);
        HttpResponse response = HttpClientUtil.refondPost("https://api.mch.weixin.qq.com/secapi/pay/refund", xmData);
//        System.out.println("请求发出去了");
        HttpEntity entity = response.getEntity();
        String return_str = EntityUtils.toString(entity, "UTF-8");
        Map<String, Object> rt_map = Xml_MapUtils.xmlToMap(return_str);
        System.out.println(rt_map);
//        System.out.println(rt_map.get("result_code").toString());
        if (rt_map.get("result_code").equals("SUCCESS")) {
            userService.updateOrderToTuikuan(rt_map.get("out_refund_no").toString(), rt_map.get("out_trade_no").toString());
            map.put("code", 0);
            map.put("msg", "退款成功");
            return map;
        }
//        System.out.println("------我是底线--------");
        map.put("code", -1);
        map.put("msg", rt_map.get("err_code_des").toString());
        return map;
    }

    //        o87G94jPEDCbM78QLqNilhbil7cs
    @RequestMapping("UpdateOrderSales")
    public Map<String, Object> UpdateOrderSales(int order_grade, String sales, int order_id) {
        Map<String, Object> map = new HashMap<>();
        if (userService.UpdateOrderSales(order_grade, sales, order_id) != 1) {
            map.put("code", -1);
            map.put("msg", "修改失败");
        }
        map.put("code", 0);
        map.put("msg", "修改成功");
        return map;
    }
}
